package com.zz.realm;


import com.zz.pojo.User;
import com.zz.service.UserService;
import com.zz.utils.PasswordUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1=(UsernamePasswordToken) token;
        String userName=token1.getUsername();
        String passWord=new String(token1.getPassword());
        //加密后的密码
        String md5Pass = PasswordUtil.md5(passWord, userName);

        //根据用户名和密码从数据库查去
        User login = userService.login(userName, md5Pass);
        SimpleAuthenticationInfo info=null;
        if (login!=null){
            String realName=getName();
            ByteSource byteSource=ByteSource.Util.bytes(userName);
            info=new SimpleAuthenticationInfo(userName,md5Pass,byteSource,realName);
        }
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object principal = principals.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        if("admin".equals(principal)){
            roles.add("admin");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        return info;
    }

}
